package cn.backpackerxl.easyJDBC.main;

import cn.backpackerxl.easyJDBC.util.MySQL;
import cn.backpackerxl.easyJDBC.util.SqlFactory;
import cn.backpackerxl.easyJDBC.util.StringUtil;

import java.util.*;

/**
 * @Author: backpackerxl
 * CreateTime: 2022/5/13
 * FileName: BasicQuery
 **/
public class BasicQuery {

    private BasicQuery() {

    }

    /**
     * 获得表结构
     *
     * @param name
     * @return
     */
    public static List<DescTable> descByTable(String name) {
        List<DescTable> descTables = new ArrayList<>();
        String sql = String.format("%s %s", MySQL.DESC, name);
        Executor.doExecutorSQLUtil(sql, rs -> {
            while (rs.next()) {
                Class<?>[] classes = SqlFactory.getSqlFieldClass(rs.getNString(2));
                DescTable descTable = new DescTable();
                descTable.setName(StringUtil.addHump(rs.getNString(1)));
                descTable.setClasses(classes);
                descTable.setKey(Objects.equals(rs.getNString(4), "PRI"));
                descTable.setAuto(rs.getNString(6));
                descTables.add(descTable);
            }
        });
        return descTables;
    }

    /**
     * 获得表的索引
     *
     * @param clazz
     * @return
     */
    public static Map<String, String> indexByTable(Class<?> clazz) {
        Map<String, String> fields = new HashMap<>();
        String sql = String.format("%s %s %s %s", MySQL.SHOW, MySQL.INDEX, MySQL.FROM, SqlFactory.getTableName(clazz));
        Executor.doExecutorSQLUtil(sql, rs -> {
            while (rs.next()) {
                fields.put(rs.getNString(5), rs.getNString(3));
            }
        });
        return fields;
    }

    /**
     * 获取所有表格
     *
     * @return
     */
    public static List<String> getTables() {
        List<String> res = new ArrayList<>();
        String sql = String.format("%s %s", MySQL.SHOW, MySQL.TABLES);
        Executor.doExecutorSQLUtil(sql, rs -> {
            while (rs.next()) {
                res.add(rs.getNString(1));
            }
        });
        return res;
    }
}
